/**  
 * All rights Reserved, Designed By www.tydic.com
 * @Title:  CommonController.java   
 * @Package com.axin.controller   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: axin     
 * @date:   2019年3月10日 下午2:47:50   
 * @version V1.0 
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. 
 */
package com.axin.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.axin.common.entity.JsonResult;
import com.axin.common.utils.EMailUtil;
import com.axin.common.utils.RandomUtil;
import com.axin.entity.HbKeyPair;
import com.axin.entity.HbUser;
import com.axin.entity.bo.EmailCode;
import com.axin.service.KeyPairService;
import com.axin.service.UserService;

/**
 * 
 * @Description: TODO 
 * @ClassName:  UserController
 * @author:  Axin 
 * @date:   2019年3月17日 下午8:48:44   
 * @Copyright: 2019 www.hao456.top Inc. All rights reserved.
 */

@Controller
@RequestMapping("user")
public class UserController {
	
	
	@Autowired
	private UserService userService;
	@Autowired
	private KeyPairService keyPairService;
	
	@Value("${ACCESS_KEY_ID}")
	private String ACCESS_KEY_ID;
	@Value("${ACCESS_KEY_SECRET}")
	private String ACCESS_KEY_SECRET;
	@Value("${ACCESS_PASSWORD}")
	private String ACCESS_PASSWORD;
	
	
	@Value("${EMAIL_HOST}")
	private String EMAIL_HOST;
	@Value("${EMAIL_FROM}")
	private String EMAIL_FROM;
	@Value("${EMAIL_USERNAME}")
	private String EMAIL_USERNAME;
	@Value("${EMAIL_PASSWORD}")
	private String EMAIL_PASSWORD;
	
	
	
	/**
	 * @Description: 发送邮箱验证码  
	 * @Title: sendCode   
	 * @param: @param email
	 * @param: @param request
	 * @param: @return      
	 * @return: JsonResult      
	 * @throws
	 */
	@RequestMapping(value="sendCode",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult sendCode(String email,HttpServletRequest request){
		HbUser user = this.userService.getUserByEmail(email);
		if(user!=null)
			return new JsonResult(new RuntimeException("该邮箱已经注册，请直接登录。"));
		String code = RandomUtil.generalNumber(6);
		String subject="注册验证码通知";
		String context = "自动化交易系统邮箱注册验证码为:"+code;
		try {
			EMailUtil.send(EMAIL_HOST, EMAIL_FROM, EMAIL_USERNAME, EMAIL_PASSWORD, subject, context, email);
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(new RuntimeException("验证码发送失败，请重试！"));
		}
		HttpSession session = request.getSession();
		EmailCode ec = new EmailCode(email,code);
		session.setAttribute("ec", ec);
		return new JsonResult();
	}
	
	/**
	 * 比较验证码
	 * @Description: TODO  
	 * @Title: verify   
	 * @param: @param email
	 * @param: @param code
	 * @param: @return      
	 * @return: JsonResult      
	 * @throws
	 */
	@RequestMapping(value="verifyCode",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult verifyCode(String email, String code,HttpServletRequest request){
		HttpSession session = request.getSession();
		EmailCode ec = (EmailCode) session.getAttribute("ec");
		if(ec == null)
			return new JsonResult(new RuntimeException("验证码已失效，请重新获取。"));
		String sessionEmail = ec.getEmail();
		String sessionCode = ec.getCode();
		if(sessionEmail.equals(email) && sessionCode.equals(code)){
			return new JsonResult();
		}
		return new JsonResult(new RuntimeException("验证码错误！"));
	}
	
	
	/**
	 * 注册
	 * @Description: TODO  
	 * @Title: register   
	 * @param: email
	 * @param: password
	 * @param: request
	 * @return: JsonResult      
	 * @throws
	 */
	@RequestMapping(value="register",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult register(HbUser user,HttpServletRequest request){
		this.userService.createUser(user);
		HttpSession session = request.getSession();
		session.removeAttribute("ec");
		return new JsonResult();
	}
	
	/**
	 * 登录
	 * @Description: TODO  
	 * @Title: login   
	 * @param: email
	 * @param: password
	 * @param: request
	 * @param: response
	 * @return: JsonResult      
	 * @throws
	 */
	@RequestMapping(value="login",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult login(String email, String password,
				HttpServletRequest request, HttpServletResponse response){
		HbUser user = userService.getUserByEmail(email);
		if(user == null){
			return new JsonResult(new RuntimeException("账号不存在！"));
		}
		String pass = user.getPassword();
		String newPassword = DigestUtils.md5DigestAsHex(password.getBytes());
		if(!pass.equals(newPassword)){
			return new JsonResult(new RuntimeException("账号或密码错误！"));
		}
		
		HttpSession session = request.getSession();
		session.setAttribute("user", user);
		//TODO
		//查询密钥对
		HbKeyPair KP = this.keyPairService.getKeyPairByUserId(user.getId());
		if(KP != null){
			session.setAttribute("kPair", KP);
		}
		return new JsonResult();
	}
	
	/**
	 * 退出用户
	 * @Description: TODO  
	 * @Title: logout   
	 * @param request
	 * @param response void
	 * @throws
	 */
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response){
		try {
			request.getSession().invalidate();
			response.sendRedirect("/login");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
